package v1

import (
	"copper-cloud/models"
	"copper-cloud/pkg/app"
	"copper-cloud/pkg/e"
	"copper-cloud/pkg/logging"
	"copper-cloud/pkg/util"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func AddRole(c *gin.Context) {
	traceId := util.GetTraceID(c)
	appG := app.Gin{C: c}

	roleName := c.Query("role_name")
	if roleName == "" {
		appG.Response(http.StatusBadRequest, e.InvalidParams, traceId, nil)
		return
	}

	isExisted := models.CheckRoleIsExisted(roleName)
	if isExisted {
		appG.Response(http.StatusBadRequest, e.InvalidParams, traceId, nil)
		return
	}

	r := models.Role{
		RoleName: roleName,
	}
	err := models.RoleInsert(r)

	if err != nil {
		appG.Response(http.StatusInternalServerError, e.ERROR, traceId, nil)
		return
	}

	appG.Response(http.StatusOK, e.SUCCESS, traceId, nil)
}


func GetAllRoles(c *gin.Context) {
	traceId := util.GetTraceID(c)
	appG := app.Gin{C: c}

	httpCode := http.StatusOK
	errCode := e.SUCCESS

	roles, err := models.RoleSelects()
	if err != nil {
		httpCode = http.StatusInternalServerError
		errCode = e.ERROR

		appG.Response(httpCode, errCode, traceId, nil)
		return
	}

	appG.Response(httpCode, errCode, traceId, roles)
}

func GetRoleById(c *gin.Context) {
	traceId := util.GetTraceID(c)
	appG := app.Gin{C: c}

	httpCode := http.StatusOK
	errCode := e.SUCCESS

	roleId, paramErr := strconv.Atoi(c.Param("role_id"))
	logging.ZapLogger.Info("roleId: ", roleId)

	if paramErr != nil {
		httpCode = http.StatusBadRequest
		errCode = e.ErrorDeptIdMustBeInt

		appG.Response(httpCode, errCode, traceId, nil)
		return
	}

	role, err := models.GetRoleNameById(roleId)
	if err != nil {
		httpCode = http.StatusInternalServerError
		errCode = e.ERROR

		appG.Response(httpCode, errCode, traceId, nil)
		return
	}
	// dept为空，则表示没有找到数据
	if role == nil {

		appG.Response(http.StatusBadRequest, e.ErrorDeptNotFound, traceId, nil)
		return
	}

	appG.Response(httpCode, errCode, traceId, role)
}